import axios from '@/src/utils/uni-fetch.js';
import {
	qqminilogin,
	wxminilogin,
	zhiminilogin,
	iosLogin,
	getkefuurl,
	gethuanlianprice2,
	WxAppLogin,
	get_app_pid,
	get_app_config
} from "@/src/api/huanlian.js"
import {
	getss
} from '@/src/utils/md5.js'
export function showToast(title, icon = 'none', duration = 3500) {
	uni.showToast({
		title: title,
		icon: icon,
		duration: duration
	})
}
export async function getKefuUrl(show = true) {
	// console.log('进来了',show)
	let app = getApp();
	if (!app || !app.globalData) {
		uni.showToast({
			title: '无法获取全局数据'
		});
		return;
	}

	let kefuLink = app.globalData.kefulink;
	// console.log(kefuLink)
	if (kefuLink) {
		if (show) {
			uni.previewImage({
				urls: [kefuLink]
			});
			// console.log(kefuLink)
		} else {
			return kefuLink;
		}
	} else {
		try {
			const res = await getkefuurl()
			// console.log(res)
			if (res.err_no === 0 && res.kefu_url) {
				app.globalData.kefulink = res.kefu_url;
				if (show) {
					uni.previewImage({
						urls: [res.kefu_url]
					});
				} else {
					return res.kefu_url;
				}
			} else {
				uni.showToast({
					title: res.err_msg ? res.err_msg : '未知错误'
				});
			}
		} catch (error) {
			uni.showToast({
				title: error.message || '请求失败'
			});
		}
	}
}
export function appUpdate(globalData = null) {
	if (!globalData) {
		globalData = getApp().globalData
	}
	plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
		axios.post(
			'/common/appupdate/', {
				appVersion: plus.runtime.version,
				wigetVersion: widgetInfo.version,
				appid: globalData.appid,
				platform: globalData.platform,
				dcloud_appid: plus.runtime.appid
			}
		).then((res) => {
			globalData.appUpdate = true
			if (res.err_no == 0 && res.data.wgtUrl) {
				let header = {}
				let ss = getss()
				header['S'] = ss[0]
				header['Ss'] = ss[1]
				uni.downloadFile({
					header: header,
					url: res.data.wgtUrl,
					success: (downloadResult) => {
						if (downloadResult.statusCode === 200) {
							plus.runtime.install(downloadResult
								.tempFilePath, {
									force: false
								},
								function() {
									plus.runtime.restart();
								},
								function(e) {
									console.error('install fail...', e);
								});
						} else {
							console.log("下载失败", downloadResult)
						}
					},
					fail: (err) => {
						console.log('下载失败', err)
					}
				});
			}
			if (res.err_no == 0 && res.data.appurl) {
				uni.showModal({ //提醒用户更新  
					// title: "更新提示",
					content: res.data.note,
					success: (result) => {
						if (result.confirm) {
							plus.runtime.openURL(res.data.appurl);
						}
					}
				})
			}
		}).catch((err) => {
			// console.error(err)
		})
	});
}

export async function getUser(data, force = false, globalData = null) {
	if (!globalData) {
		let app = getApp();
		if (!app || !app.globalData) {
			uni.showToast({
				title: '无法获取全局数据'
			});
			return;
		}
		globalData = app.globalData
	}

	let userData = globalData.userData;
	if (userData && !force) { //如果不是强制刷新，并且本地有用户信息，就返回本地的用户信息
		return userData
	} else {
		try {
			let res = null
			let initData = data || {};
			let new_data = {
				"globalData": {
					...globalData
				},
				...initData
			}
			// #ifdef APP
			if (globalData.platform == 'ios') {
				res = await iosLogin(new_data)
			} else {
				res = await WxAppLogin(new_data)
			}
			// #endif
			// #ifdef MP-WEIXIN
			res = await wxminilogin(new_data)
			// #endif
			// #ifdef MP-ALIPAY
			res = await zhiminilogin(new_data)
			// #endif
			// #ifdef MP-QQ
			res = await qqminilogin(new_data)
			// #endif
			if (res.err_no === 0) {
				if (res.data.status != 1) {
					uni.reLaunch({
						url: `/src/pages/My/AccountError/AccountError?err_msg=${res.err_msg}&uid=${res.data.uid}&kefu_url=${encodeURIComponent(res.data.kefu_url)}`
					})
					return
				}
				globalData.userData = res.data;
				// console.log(globalData)
				uni.setStorageSync('jwt_token', res.data.jwt_token)
				uni.$emit('userUpdate', {
					userData: res.data
				})
				return res.data
			} else {
				uni.showToast({
					title: res.err_msg ? res.err_msg : '未知错误'
				});
			}
		} catch (e) {
			if (!e) return
			console.log(e)
			console.error(
				`[getUser] 发生异常:\n` +
				`类型: ${e.name}\n` +
				`消息: ${e.message}\n` +
				`调用栈: ${e.stack || '无调用栈信息'}` // 关键：这里会显示错误位置
			);
			uni.showModal({
				content: e.errMsg || e.message,
				showCancel: false
			});
		}
	}
}
export function initUserData(globalData) {
	if (globalData.userData) {} else if (uni.getStorageSync('jwt_token')) {
		getUser(null, false, globalData)
	} else {
		// #ifdef MP-WEIXIN
		try {
			uni.login({
				provider: 'weixin',
				success(res) {
					getUser({
						code: res.code,
						pid: uni.getStorageSync('pid')
					}, true, globalData)
				}
			});
		} catch (error) {
			console.error('登录失败', error);
		}
		// #endif
		// #ifdef MP-ALIPAY
		try {
			uni.login({
				scopes: 'auth_base',
				success(res) {
					getUser({
						code: res.authCode
					}, true, globalData)
				}
			});
		} catch (error) {
			console.error('登录失败', error);
		}
		// #endif
	}

}
export async function getPid(globalData) {
	// #ifdef APP
	let new_data = {
		globalData: globalData,
	}
	try {
		let res = await get_app_pid(new_data)
		// console.log(res)
		if (res.err_no == 0 && res.data) {
			uni.setStorageSync('pid', res.data)
		}
	} catch (e) {
		console.error(e)
	}
	// #endif
	// #ifdef MP-WEIXIN
	let options = uni.getLaunchOptionsSync();
	if (options.query.scene) {
		let scene = decodeURIComponent(options.query.scene)
		let pid = scene.split("=")[1]
		uni.setStorageSync('pid', pid)
	}
	// #endif


}
export function jumpto(url) {
	if (!getApp().globalData.userData) {
		url = '/src/pages/My/login/login'
	}
	uni.navigateTo({
		url: url,
		fail(e) {
			uni.switchTab({
				url:url
			})
			console.log(e)
		}
	})
}
export function CustomError(errorNo, message) {
	let error = new Error('自定义异常');
	error.errCode = errorNo;
	error.errMsg = message;
	return error;
}
export async function getAppConfig(force = false) {
	let app = getApp();
	if (!app || !app.globalData) {
		uni.showToast({
			title: '无法获取全局数据'
		});
		return null;
	}
	if (app.globalData.app_config && !force) {
		return app.globalData.app_config
	} else {
		let res = await get_app_config()
		if (res && res.data) {
			app.globalData.app_config = res.data
			return res.data
		} else {
			return null
		}

	}
}

export async function getAbilityPrice(key) {
	let abilityPrice = getApp().globalData.AbilityPrice
	if (abilityPrice) {
		return abilityPrice[key]
	} else {
		try {
			let res = await gethuanlianprice2({
				v: 'v2'
			})
			if (res.err_no == 0 && res.data) {
				getApp().globalData.AbilityPrice = res.data.price
				return res.data.price[key]
			} else {
				uni.showToast({
					title: res.err_msg ? res.err_msg : '未知错误'
				});
			}
		} catch (e) {
			//TODO handle the exception
			uni.showToast({
				title: error.errMsg || '请求失败'
			});
		}
	}
}